import React, { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Button, Image } from '@tarojs/components'
import { AtActionSheet, AtActionSheetItem } from 'taro-ui'
import wx from "../../pages/my/image/wx.png"


export default class Logins extends Component {
  state = {
    nickName: '',
    avatarUrl: '',
    openId: '',
    occupation: '普通用户',
    hasUserInfo: false, // 用于判断用户是否 登录，
  }

  componentWillMount () { }

  componentDidMount () { }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }


  getLogin = () => {
    const that = this
    Taro.showModal({
      title: '温馨提示',
      content: '亲，授权微信登录后才能正常使用该小程序功能',
      success (res) {
        console.log(0)
        // 如果用户点击了确定按钮
        if (res.confirm) {
          Taro.getUserProfile({
            desc: '获取你的昵称、头像、地区及性别',
            success: (res) => {
              const user = res.userInfo
              console.log('use:', user)
              // 获取openid
              that.setCode()
              // 给本state赋值
              that.setState({
                nickName: user.nickName,
                avatarUrl: user.avatarUrl,
                hasUserInfo: true,
              })
              // 调用云函数,向数据库插入数据
              Taro.cloud
                .callFunction({
                  name: 'login',
                  data: {
                    $url: 'addUser',
                    userInfo: that.state
                  }
                })
                .then(() => {
                  that.setState({
                    nickName: user.nickName,
                    avatarUrl: user.avatarUrl,
                    openId: user.openId,
                  })
                  // 用户的部分数据存入缓存
                  Taro.setStorageSync('userInfo', that.state)
                  // 登录成功后会自动跳转到个人中心
                  if (that.state.hasUserInfo) {
                    Taro.navigateTo({
                      url: '/pages/my/index'
                    })
                  }
                })
            },
            fail: (res) => {
              console.log(2);
              console.log(res)
              // 拒绝授权
              Taro.showToast({
                title: '您拒绝了请求,不能正常使用小程序',
                icon: 'error',
                duration: 2000
              });
              return;
            }
          });
        } else if (res.cancel) {
          // 如果用户点击了取消按钮
          console.log(3);
          Taro.showToast({
            title: '您拒绝了请求,不能正常使用小程序',
            icon: 'error',
            duration: 2000
          });
          return;
        }
      }
    })


  }
  setCode () {
    const that = this
    // 获取appid
    const appId = Taro.getAccountInfoSync().miniProgram.appId;
    const appSecret = 'dba95a6e1a325401953543e50afb57e4'
    // 调用wx.login获取code
    Taro.login({// 重新登录
      success (res) {
        if (res.code) {
          let userCode = res.code
          // 发起网络请求
          Taro.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + appSecret + '&js_code=' + userCode + '&grant_type=authorization_code',
            success (res) {
              console.log('用户的openid:' + res.data.openid)
              // 载入缓存
              Taro.setStorageSync('openid', res.data.openid)
              console.log('res.data', res.data)
              that.state.openId = res.data.openid
              console.log(that.state)
            }
            // data: {
            //   jsCode: res.code
            // }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  }


  getAccess_token = () => {
    console.log('getAccess_token已被调用')
    // 获取appid,appSecret
    const appId = Taro.getAccountInfoSync().miniProgram.appId;
    const appSecret = 'dba95a6e1a325401953543e50afb57e4'
    Taro.login({
      success (res) {
        if (res.code) {
          // 发起网络请求
          console.log('code:' + res.code)
          const code = res.code
          Taro.request({
            // 获取ACCESS_TOKEN
            url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appId + '&secret=' + appSecret,
            success (res) {
              const access_token = res.data.access_token
              // 存入缓存
              Taro.setStorageSync('access_token', access_token)
              console.log('ACCESS_TOKEN:', res.data.access_token)
              return access_token
            }
          })
        } else {
          console.log('获取用户登录态失败！', res.errMsg)
        }
      }
    });
  }

  getPhoneNumber = (e) => {
    // 获取Access_token
    // this.getAccess_token()
    console.log(e)
    let ivObj = e.detail.iv
    let telObj = e.detail.encryptedData
    // 调用getAccess_token
    // const {access_token, code,appId,appSecret} = this.getAccess_token.arguments
    const access_token = Taro.getStorageSync('access_token')
    // 获取appid,appSecret
    const appId = Taro.getAccountInfoSync().miniProgram.appId;
    const appSecret = 'dba95a6e1a325401953543e50afb57e4'
    // const code = accesstoken
    Taro.login({
      success (res) {
        // 获取电话号码,post请求方式
        Taro.request({
          // +"code="+code
          url: 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' + access_token,
          data: {
            appid: appId,
            secret: appSecret,
            code: res.code,
            encryptedData: telObj,
            iv: ivObj
          },
          // post请求
          method: 'POST',
          header: {
            'content-type': 'application/json' // 默认值
          },
          success (res) {
            console.log(res.data.phoneNumber)
            console.log(res.data)
          }
        })
      }
    })
  }

  render () {
    return (
      <View className='user'>
        {/* <View className="tx">
          <Image className="face" src={this.state.avatarUrl}></Image>
          <View className='nickName'> {this.state.nickName}</View>
        </View> */}

        <View style="display:flex;">
          <Button type='primary' lang='zh_CN' onClick={this.getLogin} style="display:flex;border-radius:25px;width:260px;justify-content: flex-start;">
            <View style="height:auto;width:100%;display:flex;align-items: center;justify-content: center;">
              <View style="height:45px;width:auto;display:flex;align-items: center;">
                <Image style="height:25px;width:30px;display:flex;align-items: center;" src={wx}></Image>
              </View>
              <View style="margin-left: 20px;">微信账号快速登录</View>
            </View>
          </Button>
        </View>

        {/* <View style=" margin-top:10%">
          <Button type="primary" open-type="getPhoneNumber" onGetPhoneNumber="getPhoneNumber" onClick={this.getPhoneNumber}>
            手机号登录
          </Button>
          <Button type="primary" openType="getPhoneNumber" OnGetPhoneNumber={this.getPhoneNumber} onClick={this.getPhoneNumber}>微信绑定手机号登录</Button>
        </View>*/}
      </View>
    )
  }
}


